package com.ruoyi.manage.organization.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StrUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.manage.enterprise.domain.SysUserExpand;
import com.ruoyi.manage.enterprise.service.ISysUserExpandService;
import com.ruoyi.manage.organization.domain.*;
import com.ruoyi.manage.organization.domain.vo.BizOrganizationVo;
import com.ruoyi.manage.organization.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * 金融机构信息Controller
 *
 * @author ruoyi
 * @date 2025-08-14
 */
@Api(tags = "金融机构信息控制器")
@RestController
@RequestMapping("/manage/organization")
public class BizOrganizationController extends BaseController {
    /**
     * 配置表别名 默认空
     */
    private final static String TABLE_PREFIX = StrUtil.initTableAlias(null);
    @Autowired
    private IBizOrganizationService bizOrganizationService;

    @Autowired
    private IBizOrganizationAuditService bizOrganizationAuditService;

    @Autowired
    private IOcOrderCreditService iOcOrderCreditService;

    @Autowired
    private IOcOrderLoanService iOcOrderLoanService;

    @Autowired
    private IOcOrderRepaymentService iOcOrderRepaymentService;

    @Autowired
    private ISysUserExpandService iSysUserExpandService;


    /**
     * 查询金融机构信息列表
     */
    @ApiOperation(value = "查询金融机构信息", notes = "金融机构信息管理")
//    @PreAuthorize("@ss.hasPermi('manage:organization:list')" )
    @GetMapping("/list")
    public TableDataInfo list(BizOrganizationVo bizOrganization, QueryWrapper<BizOrganization> queryWrapper) {
        setQueryCondition(bizOrganization, queryWrapper);
        startPage();
        /*List<BizOrganization> list = bizOrganizationService.list(queryWrapper);
        for (BizOrganization organization : list) {
            organization.setBizOrganizationAuditList(bizOrganizationAuditService.list(new QueryWrapper<BizOrganizationAudit>().eq("org_id",organization.getId())));
        }*/
        List<BizOrganizationVo> list = bizOrganizationService.lists(queryWrapper);
        return getDataTable(list);
    }

    @ApiOperation(value = "查询金融机构信息", notes = "金融机构信息管理")
//    @PreAuthorize("@ss.hasPermi('manage:organization:list')" )
    @GetMapping("/listOrganizationByUser")
    public TableDataInfo listOrganizationByUser(BizOrganizationVo bizOrganization, QueryWrapper<BizOrganization> queryWrapper) {
        setQueryCondition(bizOrganization, queryWrapper);

        SysUserExpand sysUserExpand = iSysUserExpandService.lambdaQuery().eq(SysUserExpand::getUserId, SecurityUtils.getUserId()).one();

        queryWrapper.apply("INSTR(org_path, {0}) > 0", sysUserExpand.getDataPermission());

        startPage();
        List<BizOrganization> list = bizOrganizationService.list(queryWrapper);
        return getDataTable(list);
    }


    @ApiOperation(value = "查询金融机构人员信息", notes = "金融机构人员信息")
    @GetMapping("/listByUserId")
    public TableDataInfo listByUserId(BizOrganizationMember organizationMember, QueryWrapper<BizOrganizationMember> queryWrapper) {
        if (StrUtil.isNotBlank(organizationMember.getRelatedRemark())) {
            queryWrapper.like("e.related_remark", organizationMember.getRelatedRemark());
        }

        if (StrUtil.isNotBlank(organizationMember.getRelatedId())) {
            queryWrapper.like("e.related_id", organizationMember.getRelatedId());
        }

        if (StrUtil.isNotBlank(organizationMember.getNickName())) {
            queryWrapper.like("u.nick_name", organizationMember.getNickName());
        }

        if (ObjUtil.isNotNull(organizationMember.getEnabled())) {
            queryWrapper.eq("u.enabled", organizationMember.getEnabled());
        }

        if (StrUtil.isNotBlank(organizationMember.getAudit())) {
            queryWrapper.eq("si.audit", organizationMember.getAudit());
        }

        if (ObjUtil.isNotNull(organizationMember.getCreateTimeRange()) && organizationMember.getCreateTimeRange().length == 2) {
            String[] createRange = organizationMember.getCreateTimeRange();
            queryWrapper.between("u.create_time", createRange[0], createRange[1]);
        }

        if (ObjUtil.isNotNull(organizationMember.getAuditTimeRange()) && organizationMember.getAuditTimeRange().length == 2) {
            String[] auditRange = organizationMember.getAuditTimeRange();
            queryWrapper.between("si.audit_time", auditRange[0], auditRange[1]);
        }

        startPage();
        List<BizOrganizationMember> list = bizOrganizationService.selectOrganizationMember(queryWrapper);
        return getDataTable(list);
    }

    @ApiOperation(value = "查询金融机构人员信息", notes = "金融机构人员信息")
    @GetMapping("/listUser")
    public TableDataInfo listUser(BizOrganizationMember organizationMember, QueryWrapper<BizOrganizationMember> queryWrapper) {
        if (StrUtil.isNotBlank(organizationMember.getRelatedRemark())) {
            queryWrapper.like("e.related_remark", organizationMember.getRelatedRemark());
        }

        if (StrUtil.isNotBlank(organizationMember.getNickName())) {
            queryWrapper.like("u.nick_name", organizationMember.getNickName());
        }

        if (ObjUtil.isNotNull(organizationMember.getEnabled())) {
            queryWrapper.eq("u.enabled", organizationMember.getEnabled());
        }

        if (StrUtil.isNotBlank(organizationMember.getAudit())) {
            queryWrapper.eq("si.audit", organizationMember.getAudit());
        }

        if (ObjUtil.isNotNull(organizationMember.getCreateTimeRange()) && organizationMember.getCreateTimeRange().length == 2) {
            String[] createRange = organizationMember.getCreateTimeRange();
            queryWrapper.between("u.create_time", createRange[0], createRange[1]);
        }

        if (ObjUtil.isNotNull(organizationMember.getAuditTimeRange()) && organizationMember.getAuditTimeRange().length == 2) {
            String[] auditRange = organizationMember.getAuditTimeRange();
            queryWrapper.between("si.audit_time", auditRange[0], auditRange[1]);
        }

        startPage();
        List<BizOrganizationMember> list = bizOrganizationService.selectOrganizationMember2(queryWrapper);
        return getDataTable(list);
    }


    @GetMapping("/listTree")
    public AjaxResult listTree(BizOrganizationVo bizOrganization, QueryWrapper<BizOrganization> queryWrapper) {
        setQueryCondition(bizOrganization, queryWrapper);
        List<Tree<Long>> nodeTree = bizOrganizationService.getNodeTree();
        return AjaxResult.success(nodeTree);
    }

    private void setQueryCondition(BizOrganizationVo bizOrganization, QueryWrapper<BizOrganization> queryWrapper) {
        if (bizOrganization.getOrgType() != null) {
            queryWrapper.eq(TABLE_PREFIX + "org_type", bizOrganization.getOrgType());
        }
        if (StrUtil.isNotBlank(bizOrganization.getOrgPath())) {
            queryWrapper.like(TABLE_PREFIX + "org_path", bizOrganization.getOrgPath());
        }
        if (bizOrganization.getLevel() != null) {
            queryWrapper.eq(TABLE_PREFIX + "level", bizOrganization.getLevel());
        }
        if (StrUtil.isNotBlank(bizOrganization.getOrgName())) {
            queryWrapper.like(TABLE_PREFIX + "org_name", bizOrganization.getOrgName());
        }
        if (StrUtil.isNotBlank(bizOrganization.getProvince())) {
            queryWrapper.like(TABLE_PREFIX + "province", bizOrganization.getProvince());
        }
        if (StrUtil.isNotBlank(bizOrganization.getCity())) {
            queryWrapper.like(TABLE_PREFIX + "city", bizOrganization.getCity());
        }
        if (StrUtil.isNotBlank(bizOrganization.getDistrict())) {
            queryWrapper.like(TABLE_PREFIX + "district", bizOrganization.getDistrict());
        }
        if (bizOrganization.getStatus() != null) {
            queryWrapper.eq(TABLE_PREFIX + "status", bizOrganization.getStatus());
        }
        if (StrUtil.isNotBlank(bizOrganization.getAudit())) {
            queryWrapper.eq("b.audit", bizOrganization.getAudit());
        }
        queryWrapper.orderByDesc(TABLE_PREFIX + "create_time");
    }

    @GetMapping("/getCreditLoanRepay")
    public AjaxResult getRecordIncludesCreditLoanRepay(String orderNo) {
        HashMap<String, Object> map = new HashMap<>();
        OcOrderCredit orderCredit = iOcOrderCreditService.getOne(new QueryWrapper<OcOrderCredit>().eq("order_no", orderNo), false);
        map.put("orderCredit", orderCredit);
        List<OcOrderLoan> ocOrderLoans = iOcOrderLoanService.list(new QueryWrapper<OcOrderLoan>().eq("order_no", orderNo));
        map.put("ocOrderLoans", ocOrderLoans);
        List<OcOrderRepayment> orderRepayments = iOcOrderRepaymentService.list(new QueryWrapper<OcOrderRepayment>().eq("order_no", orderNo));
        map.put("orderRepayments", orderRepayments);
        return AjaxResult.success(map);
    }

    /**
     * 导出金融机构信息列表
     */
    @PreAuthorize("@ss.hasPermi('manage:organization:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizOrganizationVo bizOrganization, QueryWrapper<BizOrganization> queryWrapper) {
        if (CollUtil.isEmpty(bizOrganization.getIds())) {
            setQueryCondition(bizOrganization, queryWrapper);
        } else {
            queryWrapper.in(TABLE_PREFIX + "id", bizOrganization.getIds());
        }
        List<BizOrganization> list = bizOrganizationService.list(queryWrapper);
        ExcelUtil<BizOrganization> util = new ExcelUtil<BizOrganization>(BizOrganization.class);
        util.exportExcel(response, list, "organization");
    }

    /**
     * 获取金融机构信息详细信息
     */
    @ApiOperation(value = "获取金融机构信息", notes = "金融机构信息管理")
    @PreAuthorize("@ss.hasPermi('manage:organization:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(bizOrganizationService.queryGetById(id));
    }

    /**
     * 新增金融机构信息
     */
    @ApiOperation(value = "新增金融机构信息", notes = "金融机构信息管理")
    @PreAuthorize("@ss.hasPermi('manage:organization:add')")
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@Validated @RequestBody BizOrganization bizOrganization) {
        return toAjax(bizOrganizationService.addBizOrganization(bizOrganization) ? 1 : 0);
    }

    /**
     * 新增金融机构信息
     */
    @ApiOperation(value = "新增金融机构信息", notes = "金融机构信息管理")
    @RepeatSubmit
    @PostMapping("/appAdd")
    public AjaxResult addApp(@Validated @RequestBody BizOrganization bizOrganization) {
        return toAjax(bizOrganizationService.addBizOrganizationByApp(bizOrganization) ? 1 : 0);
    }

    /**
     * 新增金融机构信息
     */
    @ApiOperation(value = "新增金融机构信息", notes = "金融机构信息管理")
    @RepeatSubmit
    @PostMapping("/appUdp")
    public AjaxResult appUdp(@Validated @RequestBody BizOrganization bizOrganization) {
        return toAjax(bizOrganizationService.updateBizOrganizationByApp(bizOrganization) ? 1 : 0);
    }

    /**
     * 修改金融机构信息
     */
    @ApiOperation(value = "修改金融机构信息", notes = "金融机构信息管理")
    @PreAuthorize("@ss.hasPermi('manage:organization:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody BizOrganization bizOrganization) {
        return toAjax(bizOrganizationService.updateBizOrganization(bizOrganization) ? 1 : 0);
    }

    /**
     * 审核金融机构信息
     */
    @ApiOperation(value = "审核金融机构信息", notes = "金融机构信息管理")
    @PreAuthorize("@ss.hasPermi('manage:organization:edit')")
    @PostMapping("/check")
    public AjaxResult check(@RequestBody BizOrganizationVo bizOrganization) {
        bizOrganizationService.check(bizOrganization);
        return AjaxResult.success();
    }

    /**
     * 删除金融机构信息
     */
    @ApiOperation(value = "删除金融机构信息", notes = "金融机构信息管理")
    @PreAuthorize("@ss.hasPermi('manage:organization:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(bizOrganizationService.deleteBizOrganizationByIds(ids) ? 1 : 0);
    }
}
